package com.yexiao.core.exception;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class BusinessException extends RuntimeException{
    private static final int DEFAULT_CODE = 666;

    private Integer code;

    private String msg;

    private Object data;

    public BusinessException(String msg) {
        this(DEFAULT_CODE, msg, null);
    }

    public BusinessException(int code, String msg) {
        this(code, msg, null);
    }


    public BusinessException(int code, String msg, Object data) {
        super(msg);
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    @Override
    public String getMessage() {
        return StrUtil.format("{}|{}{}",
                code,
                msg,
                data == null ? "" : "|" + toJSON(data)
        );
    }

    public String toJSON(Object obj) {
        if (obj == null) {
            return null;
        } else {
            return obj instanceof String ? (String)obj : JSON.toJSONString(obj);
        }
    }
}

